# from .setting import mqtthost
# 为了能在外部脚本中调用Django ORM模型，必须配置脚本环境变量，将脚本注册到Django的环境变量中
import os
from threading import Thread

import django
from paho.mqtt.client import Client

# 第一个参数固定，第二个参数是工程名称.settings
# os.environ.setdefault('DJANGO_SETTING_MODULE', 'lot.settings')
# django.setup()


class mqttContoller(Client):
    def __init__(self, host, topic):
        self.host = host
        self.topic = topic
        Client.__init__(self)
        self.on_message = self.receivedmessagemethod

    def connecttohost(self):
        self.connect(self.host)
        self.subscribe(topic=self.topic, qos=2)

    def receivedmessagemethod(self, client, userdata, message):
        # TODO finish the method here
        print('topic: ' + message.topic)
        print('payload: ' + message.payload.decode('utf8'))


def MQTTStart():
    client = mqttContoller(host='dashiandjie.top', topic='gateway')
    client.connecttohost()
    client.loop_forever()


def MQTTThread():
    MQTTthread = Thread(target=MQTTStart())
    MQTTthread.start()


if __name__ == '__main__':
    MQTTThread()